package com.sky.Aspact;

import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import com.sky.utils.AutoFill;
import javassist.bytecode.SignatureAttribute;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspact {
    @Pointcut(value = "execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.utils.AutoFill)")
    public void point(){

    }
    @Before("point()")
    public void autoFill(JoinPoint joinPoint){
        MethodSignature signature =(MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();

        Object emtry = joinPoint.getArgs()[0];

        LocalDateTime now=LocalDateTime.now();
        Long id= BaseContext.getCurrentId();
        if(operationType.equals(operationType.UPDATE)){
            try {
                Method setUpdateUser=emtry.getClass().getDeclaredMethod("setUpdateUser",Long.class);
                Method setUpdateTime=emtry.getClass().getDeclaredMethod("setUpdateTime",LocalDateTime.class);

                setUpdateUser.invoke(emtry,id);
                setUpdateTime.invoke(emtry,now);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }else if(operationType.equals(operationType.INSERT)){
            try {
                Method setCreateUser=emtry.getClass().getDeclaredMethod("setCreateUser",Long.class);
                Method setCreateTime=emtry.getClass().getDeclaredMethod("setCreateTime",LocalDateTime.class);
                Method setUpdateUser=emtry.getClass().getDeclaredMethod("setUpdateUser",Long.class);
                Method setUpdateTime=emtry.getClass().getDeclaredMethod("setUpdateTime",LocalDateTime.class);

                setCreateUser.invoke(emtry,id);
                setCreateTime.invoke(emtry,now);
                setUpdateUser.invoke(emtry,id);
                setUpdateTime.invoke(emtry,now);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        log.info("开始填充");
    }
}
